package com.project.im.common.util;

import com.project.im.app.dto.WebUserDetails;
import com.project.im.web.filter.WebUserAuthenticationToken;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.function.Function;

@UtilityClass
public class SecurityUtils {

    public <T> T getAuthentication(Class<T> clazz) {
        return clazz.cast(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
    }

    public <T, R> R getValue(Class<T> clazz, Function<T, R> getFunc) {
        T t = getAuthentication(clazz);
        return getFunc.apply(t);
    }

    public void setAuthentication(WebUserDetails webUserDetails) {
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(new WebUserAuthenticationToken(webUserDetails, webUserDetails.getAuthorities()));
        SecurityContextHolder.setContext(context);
    }

}
